package tornadoj.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tornadoj.points.IDownload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * http 轻量级下载类
 * Created by i@tinyms.com on 2014/11/12.
 */
public class Http {
    private static Logger logger = LoggerFactory.getLogger(Http.class);
    public static String cachePath = "d:/temp";

    public static void download(String url, IDownload iDownload){
        List<String> urls = new ArrayList<String>();
        urls.add(url);
        downloads(urls, iDownload);
    }
    public static void downloads(List<String> waitForDownloadFileUrls, final IDownload iDownload) {
        if (waitForDownloadFileUrls == null) {
            return;
        }
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 3, 0L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(25), new ThreadPoolExecutor.DiscardOldestPolicy());
        for (final String url : waitForDownloadFileUrls) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    logger.info(String.format("Download %s", url));
                    CloseableHttpClient httpclient = HttpClients.createDefault();
                    HttpGet httpget = new HttpGet(url);
                    httpget.setHeader("Accept", "text/html, */*; q=0.01");
                    httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
                    httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
                    httpget.setHeader("Connection", "keep-alive");
                    httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36");
                    CloseableHttpResponse response = null;
                    try {
                        response = httpclient.execute(httpget);
                        int status = response.getStatusLine().getStatusCode();
                        logger.info(response.getStatusLine().toString());
                        if(status == HttpStatus.SC_OK){
                            HttpEntity entity = response.getEntity();
                            if (entity != null) {
                                try (BufferedInputStream instream = new BufferedInputStream(entity.getContent())) {
                                    byte[] data = IOUtils.toByteArray(instream);
                                    String targetFile = String.format("%s/%s.dl", cachePath, Utils.md5(url));
                                    IOUtils.write(data, new FileOutputStream(new File(targetFile)));
                                    if(iDownload != null){
                                        File f = new File(targetFile);
                                        if(!f.exists()){
                                            logger.info("File exists?");
                                            return;
                                        }
                                        boolean b = iDownload.doInDownload(targetFile);
                                        if(b){
                                            FileUtils.deleteQuietly(new File(targetFile));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        if (response != null) {
                            try {
                                response.close();
                            } catch (IOException e1) {
                                logger.info(e1.getLocalizedMessage(), e1);
                            }
                        }
                    }
                }
            });
        }
        try {
            threadPool.shutdown();
            while (!threadPool.awaitTermination(1, TimeUnit.SECONDS)) {
                System.out.print("Wait for download finished..\r");
            }
        } catch (InterruptedException e) {
            logger.info(e.getLocalizedMessage(), e);
        }
        System.out.println();
    }
}
